$(function () {

    var limit = 20;
    var SEOval = '';




    function xin() {
        $.ajax({
            url: ctx + '/rentorder/selectRentOrdersCount',
            type: 'GET',
            success: function (data) {
                var text = data.split(',');
                var li = $('.CustomTabs ul li');

                if (text[0] > 0) {
                    if (li.eq(0).find('.CustomBadge').length > 0) {
                        li.eq(0).find('.CustomBadge').remove();
                        li.eq(0).Badge({data: {text: text[0] > 99 ? '99+' : text[0], state: 'No'}})
                    } else {
                        li.eq(0).Badge({data: {text: text[0] > 99 ? '99+' : text[0], state: 'No'}})
                    }
                }

                if (text[1] > 0) {
                    if (li.eq(7).find('.CustomBadge').length > 0) {
                        li.eq(7).find('.CustomBadge').remove();
                        li.eq(7).Badge({data: {text: text[1] > 99 ? '99+' : text[1], state: 'No'}})
                    } else {
                        li.eq(7).Badge({data: {text: text[1] > 99 ? '99+' : text[1], state: 'No'}})
                    }
                }

                if (text[2] > 0) {
                    if (li.eq(8).find('.CustomBadge').length > 0) {
                        li.eq(8).find('.CustomBadge').remove();
                        li.eq(8).Badge({data: {text: text[2] > 99 ? '99+' : text[2], state: 'No'}})
                    } else {
                        li.eq(8).Badge({data: {text: text[2] > 99 ? '99+' : text[2], state: 'No'}})
                    }
                }
            }
        })
    }

    xin();
    setInterval(function () {
        xin()
    }, 60000);

    ajaxFreshOrder(1, SEOval);
    function ajaxFreshOrder(page, inquireVal) {
        var FreshOrder = {
            plateNoOrPassengerPhone: inquireVal || "",
            status: 0,
            limit: limit,
            "pager.offset": (page - 1) * limit
        };
        $.ajax({
            url: ctx + '/rentorder/selectRentOrders',
            data: FreshOrder,
            type: "GET",
            success: function (data) {
                var Message = {
                    data: {
                        Thead: {
                            PullDownAction: "操作",
                            OddNumbers: "单号",
                            totalFree:'总金额',
                            payed: '租金',
                            shopName: "门店",
                            TakeCarWay: "取车地址",
                            CarWay: "还车地址",
                            bookTime: "预约时间",
                            LeaseTime: "还车时间",

                            CustomerName: "客户名称",
                            CustomerPhone: "客户电话",
                            // PlateNumbers: "车辆牌号",
                            VehicleModel: "车辆型号",
                            CharterBase: "租金标准",
                            PaysTheRent: "租车押金",
                            ViolationOfTheDeposit: "违章押金",
                            // GrantAmountInAdvance: "预授额度",
                            SubordinateCompanies: "所属公司",
                            Remark: "备注"
                        },
                        Tbody: []

                    }
                };

                for (var i = 0; i < data.content.length; i++) {
                    (function () {
                        var index = i;
                        var val = {
                            id: data.content[index].id,
                            PullDownAction: {
                                data: []
                            },
                            OddNumbers: data.content[i].orderNo,
                            totalFree:data.content[i].totalFee,
                            payed: '',
                            ShopName: data.content[i].shopName,
                            RetrievingMeans: data.content[index].takeCarWay == 1 ? data.content[index].startAddress : "门店自取",
                            ReturnType: data.content[index].backCarWay == 1 ? data.content[index].endAddress : '门店自还',
                            bookTime: $.fn.Timestamp.TimestampDate(data.content[i].bookTime),
                            LeaseTime: $.fn.Timestamp.TimestampDate(data.content[i].rentTime),

                            CustomerName: data.content[i].passengerName,
                            CustomerPhone: data.content[i].passengerPhone,
                            VehicleModel: data.content[i].category,
                            CharterBase: parseInt(data.content[i].totalFee / (Math.ceil($().Timestamp.DayCalculate(data.content[i].rentTime - data.content[i].backCarTime).split('时')[0].replace('天', '.')))),
                            PaysTheRent: data.content[i].prepayRent,
                            ViolationOfTheDeposit: data.content[i].peccancyForegift,
                            GrantAmountInAdvance: data.content[i].companyName,
                            // SubordinateCompanies: data.data[i].SubordinateCompanies,
                            Remark: data.content[i].memo
                        };


                        switch (data.content[i].isPay) {
                            case 0:
                                val.payed = $('<span class="badge">未交付</span>');
                                break;
                            case 1:
                                val.payed = data.content[i].payed;
                                break;
                            case 2:
                                val.payed =data.content[i].payed;
                                break;
                            case 3:
                                val.payed = data.content[i].payed;
                                break;
                            case 4:
                                val.payed = '已结算';
                                break;
                        }

                        if (data.content[i].isPay == 1) {
                            val.PullDownAction['Default'] = {
                                name: "确认",
                                action: function (e) {
                                    var affirmMod = {
                                        data: {
                                            Title: '确认提示',
                                            Content: '确认此订单没有问题，允许进如下一步？',
                                            OkChange: function () {
                                                $.ajax({
                                                    url: ctx + '/rentorder/confirm',
                                                    data: {
                                                        id: data.content[index].id
                                                    },
                                                    type: 'POST',
                                                    success: function (data) {
                                                        if (data.message == '确定成功') {
                                                            $('body').Overlays({data: {text: '确定成功！', state: 'Ok'}});
                                                            ajaxFreshOrder(1, SEOval);
                                                            xin();
                                                        } else {
                                                            $('body').Overlays({
                                                                data: {
                                                                    text: '确定失败，请稍后重试！',
                                                                    state: 'No'
                                                                }
                                                            });
                                                        }
                                                    }
                                                })
                                            }
                                        }
                                    };

                                    $('body').ModalBox(affirmMod)

                                }
                            };
                            val.PullDownAction.data.push({
                                name: "交租金",
                                action: function (e) {
                                    var payed = 0;
                                    var RentSum = {
                                        data: {
                                            Title: '交租金',
                                            Content: '',
                                            OkChange: function (e, Rmove) {


                                                payed = e.find('.RentSumContent input').val();
                                                var sate = true;

                                                var queren={
                                                    data:{
                                                        Title:'确认租金金额',
                                                        Content:'您确认您的租金金额是 （ '+payed+'  ）元？',
                                                        OkChange:function () {
                                                            if (!payed == '') {
                                                                $.ajax({
                                                                    url: ctx + '/rentorder/payed',
                                                                    data: {
                                                                        id: data.content[index].id,
                                                                        payed: payed
                                                                    },
                                                                    type: 'POST',
                                                                    success: function (data) {
                                                                        if (data.message == '支付成功') {
                                                                            $('body').Overlays({
                                                                                data: {
                                                                                    text: '支付成功！',
                                                                                    state: 'Ok'
                                                                                }
                                                                            });
                                                                            Rmove();
                                                                            ajaxFreshOrder(1, SEOval);
                                                                            xin();
                                                                        } else {
                                                                            Rmove();
                                                                            $('body').Overlays({
                                                                                data: {
                                                                                    text: '支付失败，请稍后重试！',
                                                                                    state: 'No'
                                                                                }
                                                                            });
                                                                        }
                                                                    }
                                                                })
                                                            } else {
                                                                $('body').Overlays({data: {text: '请输入租金金额！', state: 'No'}})
                                                            }
                                                        }
                                                    }
                                                };

                                                $('body').ModalBox(queren)

                                            }
                                        },
                                        OKHide: true,
                                        inputNumberMin:true
                                    };

                                    var RentSumContent = $('<div class="RentSumContent"></div>');
                                    RentSumContent.append('<div class="rows"><div class="name">租金额度：</div><div class="text"><input type="number" ></div></div><div class="rows warn">输入正数为支付，负数为扣除！</div>');


                                    RentSum.data.Content = RentSumContent;
                                    $('body').ModalBox(RentSum)
                                }
                            });
                            val.PullDownAction.data.push({
                                name: '查看',
                                action: function () {
                                    window.location.href = ctx + '/rentorder/orderinfo?id=' + data.content[index].id;
                                }
                            })
                        } else {
                            val.PullDownAction['Default'] = {
                                name: "交租金",
                                action: function (e) {
                                    var payed = 0;
                                    var RentSum = {
                                        data: {
                                            Title: '交租金',
                                            Content: '',
                                            OkChange: function (e, Rmove) {
                                                payed = e.find('.RentSumContent input').val();
                                                if (!payed == '') {
                                                    $.ajax({
                                                        url: ctx + '/rentorder/payed',
                                                        data: {
                                                            id: data.content[index].id,
                                                            payed: payed
                                                        },
                                                        type: 'POST',
                                                        success: function (data) {
                                                            if (data.message == '支付成功') {
                                                                $('body').Overlays({
                                                                    data: {
                                                                        text: '支付成功！',
                                                                        state: 'Ok'
                                                                    }
                                                                });
                                                                Rmove();
                                                                ajaxFreshOrder(1, SEOval);
                                                                xin();
                                                            } else {
                                                                Rmove();
                                                                $('body').Overlays({
                                                                    data: {
                                                                        text: '支付失败，请稍后重试！',
                                                                        state: 'No'
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    })
                                                } else {
                                                    $('body').Overlays({data: {text: '请输入租金金额！', state: 'No'}})
                                                }

                                            }
                                        },
                                        OKHide: true,
                                        inputNumberMin:true
                                    };

                                    var RentSumContent = $('<div class="RentSumContent"></div>');
                                    RentSumContent.append('<div class="rows"><div class="name">租金额度：</div><div class="text"><input type="number" ></div></div><div class="rows warn">输入正数为支付，负数为扣除！</div>');


                                    RentSum.data.Content = RentSumContent;
                                    $('body').ModalBox(RentSum)
                                }
                            };
                            val.PullDownAction.data.push({
                                name: '查看',
                                action: function () {
                                    window.location.href = ctx + '/rentorder/orderinfo?id=' + data.content[index].id;
                                }
                            })
                        }


                        switch (data.content[index].isBackPrepayRent) {
                            case 0:
                                val.PaysTheRent = '未交付';
                                val.PullDownAction.data.push({
                                    name: '交租车押金',
                                    action: function (e) {

                                        var prepayRentTime = '';
                                        var prepayRent = '';
                                        var prepayRentType = 1;
                                        var yajinjiluData = {
                                            data: {
                                                Title: '交租车押金',
                                                Content: '',
                                                OkChange: function (e,Remove) {
                                                    var reRentTime = '';
                                                    var huanche;

                                                    function Ajax() {
                                                        $.ajax({
                                                            url: ctx + '/rentorder/deposit',
                                                            data: huanche,
                                                            type: 'POST',
                                                            success: function (data) {
                                                                if (data.message == "押金记录录入成功") {
                                                                    ajaxFreshOrder(1, SEOval);
                                                                    $('body').Overlays({
                                                                        data: {
                                                                            text: '添加租车押金成功！',
                                                                            state: 'Ok'
                                                                        }
                                                                    });
                                                                    ajaxFreshOrder(1, SEOval);
                                                                    xin();
                                                                    Remove()
                                                                } else {
                                                                    $('body').Overlays({
                                                                        data: {
                                                                            text: '添加租车押金失败，请稍后重试！',
                                                                            state: 'No'
                                                                        }
                                                                    })
                                                                }
                                                            }
                                                        });
                                                        $('body .datepicker').remove();
                                                    }

                                                    if (prepayRentType == 1) {
                                                        huanche = {
                                                            id: data.content[index].id,
                                                            prepayRentTime: prepayRentTime,
                                                            prepayRent: prepayRent,
                                                            prepayRentType: prepayRentType
                                                        };
                                                        if(!huanche.prepayRent<=0 && !huanche.prepayRentTime==''){
                                                            Ajax()
                                                        }else {
                                                            $('body').Overlays({
                                                                data: {
                                                                    text: '请检查信息是否填写完整！',
                                                                    state: 'No'
                                                                }
                                                            });
                                                        }
                                                    } else {
                                                        huanche = {
                                                            id: data.content[index].id,
                                                            prepayRent: prepayRent,
                                                            prepayRentType: prepayRentType
                                                        };
                                                        if(!huanche.prepayRent<=0){
                                                            Ajax()
                                                        }else {
                                                            $('body').Overlays({
                                                                data: {
                                                                    text: '请检查信息是否填写完整！',
                                                                    state: 'No'
                                                                }
                                                            });
                                                        }
                                                    }




                                                    
                                                },
                                                CancelChange: function () {
                                                    $('body .datepicker').remove();
                                                }
                                            },
                                            OKHide:true,

                                        };


                                        var ModContent = $('<div class="ModContent"></div>');
                                        var YSRows = $('<div class="Rows"><div class="Name"><em>*</em>租车押金额度：</div></div>');
                                        var Content = $('<div class="RowsContent"><input class="YsInput" type="number" /></div>');
                                        Content.find('.YsInput').on('input', function () {
                                            prepayRent = $(this).val();
                                            if(prepayRent<0){
                                                $(this).val('');
                                                prepayRent=0;
                                            }
                                        });
                                        YSRows.append(Content);
                                        ModContent.append(YSRows);

                                        var YSRowsType = $('<div class="Rows"><div class="Name">交付类型：</div></div>');
                                        var Content2 = $('<div class="RowsContent CustomClear"><label><input class="rentCarInput" type="radio" name="rentCar" value="预授权" checked /><span>预授权交付</span></label><label><input class="rentCarInput" type="radio" name="rentCar" value="现金" /><span>现金交付</span></label></div>');
                                        YSRowsType.append(Content2);
                                        ModContent.append(YSRowsType);

                                        var TimeRows = $('<div class="Rows PreauthorizationTime"><div class="Name"><em>*</em>预授权到期时间：</div></div>');
                                        var Content1 = $('<div class="RowsContent"></div>');
                                        var TimeInput = $('<input class="TimeInput" type="text" readonly/>');
                                        var shijian=Date.parse(new Date())/1000;
                                        TimeInput.datetimepicker({
                                            format: "yyyy-mm-dd HH:ii",
                                            language: 'zh-CN',
                                            showMeridian: true,
                                            autoclose: true,
                                            todayBtn: true,
                                            startDate:$().Timestamp.TimestampDate(shijian)
                                        }).on('change', function () {
                                            var Titme = $(this).val();
                                            prepayRentTime = $().Timestamp.DateTimestamp(Titme);
                                        });
                                        Content1.append(TimeInput);
                                        TimeRows.append(Content1);
                                        ModContent.append(TimeRows);
                                        yajinjiluData.data.Content = ModContent;

                                        var rentCar = ModContent.find('.rentCarInput');
                                        for (var i = 0; i < rentCar.length; i++) {
                                            rentCar.eq(i).on('click', function () {
                                                switch ($(this).val()) {
                                                    case '预授权':
                                                        prepayRentType = 1;
                                                        ModContent.find('.PreauthorizationTime').css({'opacity': 1,'z-index':'100','display': 'inline-block'});
                                                        break;
                                                    case '现金':
                                                        prepayRentType = 0;
                                                        ModContent.find('.PreauthorizationTime').css({'opacity': 1,'z-index':'-100','display': 'none'});
                                                        break;
                                                }
                                            })
                                        }

                                        $('body').ModalBox(yajinjiluData);

                                    }
                                });
                                break;
                            case 1:
                                val.PaysTheRent = data.content[index].prepayRent;
                                break;
                            case 2:
                                val.PaysTheRent = '已退还';
                                break
                        }

                        switch (data.content[index].isBackPeccancyForegift) {
                            case 0:
                                val.ViolationOfTheDeposit = '未交付';
                                val.PullDownAction.data.push({
                                    name: '交违章押金',
                                    action: function (e) {


                                        var peccancyForegiftTime = '';
                                        var peccancyForegift = '';
                                        var peccancyForegiftType = 1;
                                        var yajinjiluData = {
                                            data: {
                                                Title: '交违章押金',
                                                Content: '',
                                                OkChange: function (e,Rmove) {
                                                    var reRentTime = '';
                                                    var huanche;


                                                    function Ajax() {
                                                        $.ajax({
                                                            url: ctx + '/rentorder/deposit',
                                                            data: huanche,
                                                            type: 'POST',
                                                            success: function (data) {
                                                                if (data.message == "押金记录录入成功") {
                                                                    $('body').Overlays({
                                                                        data: {
                                                                            text: '添加违章押金成功！',
                                                                            state: 'Ok'
                                                                        }
                                                                    });
                                                                    ajaxFreshOrder(1, SEOval);
                                                                    xin();
                                                                    Rmove()
                                                                } else {
                                                                    $('body').Overlays({
                                                                        data: {
                                                                            text: '添加违章押金失败，请稍后重试！',
                                                                            state: 'No'
                                                                        }
                                                                    })
                                                                }
                                                            }
                                                        });
                                                        $('body .datepicker').remove();
                                                    }
                                                    if (peccancyForegiftType == 1) {
                                                        huanche = {
                                                            id: data.content[index].id,
                                                            peccancyForegiftTime: peccancyForegiftTime,
                                                            peccancyForegift: peccancyForegift,
                                                            peccancyForegiftType: peccancyForegiftType,
                                                        };

                                                        if(!huanche.peccancyForegift<=0&&!huanche.peccancyForegiftTime==''){
                                                            Ajax()
                                                        }else {
                                                            $('body').Overlays({
                                                                data: {
                                                                    text: '请检查信息是否填写完整！',
                                                                    state: 'No'
                                                                }
                                                            });
                                                        }
                                                    } else {
                                                        huanche = {
                                                            id: data.content[index].id,
                                                            peccancyForegift: peccancyForegift,
                                                            peccancyForegiftType: peccancyForegiftType,
                                                        };
                                                        if(!huanche.peccancyForegift<=0){
                                                            Ajax()
                                                        }else {
                                                            $('body').Overlays({
                                                                data: {
                                                                    text: '请检查信息是否填写完整！',
                                                                    state: 'No'
                                                                }
                                                            });
                                                        }
                                                    }



                                                },
                                                CancelChange: function () {
                                                    $('body .datepicker').remove();
                                                }
                                            },
                                            OKHide:true
                                        };


                                        var ModContent = $('<div class="ModContent"></div>');
                                        var YSRows = $('<div class="Rows"><div class="Name"><em>*</em>违章押金额度：</div></div>');
                                        var Content = $('<div class="RowsContent"><input class="YsInput" type="number" /></div>');
                                        Content.find('.YsInput').on('input', function () {
                                            peccancyForegift = $(this).val();
                                            if(peccancyForegift<0){
                                                peccancyForegift=0;
                                                $(this).val('');
                                            }
                                        });
                                        YSRows.append(Content);
                                        ModContent.append(YSRows);

                                        var YSRowsType = $('<div class="Rows"><div class="Name">交付类型：</div></div>');
                                        var Content2 = $('<div class="RowsContent CustomClear"><label><input class="rentCarInput" type="radio" name="rentCar" value="预授权" checked /><span>预授权交付</span></label><label><input class="rentCarInput" type="radio" name="rentCar" value="现金" /><span>现金交付</span></label></div>');
                                        YSRowsType.append(Content2);
                                        ModContent.append(YSRowsType);

                                        var TimeRows = $('<div class="Rows PreauthorizationTime"><div class="Name"><em>*</em>预授权到期时间：</div></div>');
                                        var Content1 = $('<div class="RowsContent"></div>');
                                        var TimeInput = $('<input class="TimeInput" type="text" readonly/>');
                                        var shijian=Date.parse(new Date())/1000;
                                        TimeInput.datetimepicker({
                                            format: "yyyy-mm-dd HH:ii",
                                            language: 'zh-CN',
                                            showMeridian: true,
                                            autoclose: true,
                                            todayBtn: true,
                                            startDate:$().Timestamp.TimestampDate(shijian)
                                        }).on('change', function () {
                                            var Titme = $('body .CustomModalBox[custommodalboxlength="0"] .TimeInput').val();
                                            peccancyForegiftTime = $().Timestamp.DateTimestamp(Titme);
                                        });
                                        Content1.append(TimeInput);
                                        TimeRows.append(Content1);
                                        ModContent.append(TimeRows);
                                        yajinjiluData.data.Content = ModContent;

                                        var rentCar = ModContent.find('.rentCarInput');
                                        for (var i = 0; i < rentCar.length; i++) {
                                            rentCar.eq(i).on('click', function () {
                                                switch ($(this).val()) {
                                                    case '预授权':
                                                        peccancyForegiftType = 1;
                                                        ModContent.find('.PreauthorizationTime').css({'opacity': 1,'z-index':'100','display': 'inline-block'});;
                                                        break;
                                                    case '现金':
                                                        peccancyForegiftType = 0;
                                                        ModContent.find('.PreauthorizationTime').css({'opacity': 1,'z-index':'-100','display': 'none'});
                                                        break;
                                                }
                                            })
                                        }

                                        $('body').ModalBox(yajinjiluData);

                                    }
                                });
                                break;
                            case 1:
                                val.ViolationOfTheDeposit = data.content[index].peccancyForegift;
                                break;
                            case 2:
                                val.ViolationOfTheDeposit = '已退还';
                                break
                        }


                        val.PullDownAction.data.push({
                            name: "销单",
                            action: function (e) {
                                var QuCar = {
                                    data: {
                                        Title: '销单提示',
                                        Content: '你确定要销单吗？',
                                        OkChange: function () {
                                            var xiaodanOption = {
                                                id: data.content[index].id
                                            };
                                            $.ajax({
                                                url: ctx + '/rentorder/cancel',
                                                data: xiaodanOption,
                                                type: 'POST',
                                                success: function (data) {
                                                    $('body').Overlays({
                                                        data: {
                                                            text: "销单成功！",
                                                            state: 'Ok'
                                                        }
                                                    });
                                                    ajaxFreshOrder(1, SEOval);
                                                    xin();
                                                }
                                            })
                                        }
                                    }
                                };
                                $('body').ModalBox(QuCar);
                            }
                        });


                        Message.data.Tbody.push(val);
                    })();


                }

                var PagingMdOption = {
                    data: {
                        rows: 20,
                        nowrows: page,
                        Pages: '',
                        total: data.totalElements,
                        change: function (index) {
                            ajaxFreshOrder(index, SEOval);
                        }
                    }
                };
                PagingMdOption.data.Pages = Math.ceil((PagingMdOption.data.total / PagingMdOption.data.rows));

                $(".Content").find('.CustomOrder').remove();
                $(".Content").find('.PagingMdPagingMd').remove();
                $(".Content").Order(Message);
                $(".Content").PagingMd(PagingMdOption)
            }
        })
    }


    //查询-------------------------------
    $(".Nav .SEO .SEOButton").on("click", function () {
        SEOval = $(".Nav .SEO  input").val();
        ajaxFreshOrder(1, SEOval);
        xin();
    });
    //-------------------------------


    $(".Nav .SEO  input").keyup(function (event) {
        switch (event.keyCode) {
            case 13:
                $(".Nav .SEO .SEOButton").click();
                break;
        }
    });
})
;


